
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';

import '../config.dart';

class Api {
  static HttpClient client;
  static String apiServer;
  static String userAgent;
  static Map<String, String> headers=Map();

  static init(){
    client = new HttpClient();
    apiServer = Config.server;
    var version= '';
    try{
      version=Platform.version;
    }catch(ex){

    }
    userAgent = "Mozilla/5.0 (${Platform.operatingSystem}/${Platform.operatingSystemVersion} "
                "Flutter/$version ) "
                "ShirneCMS/${Config.version()} ";
    //print(userAgent);
    if(!apiServer.endsWith('/')){
      apiServer += '/';
    }

    headers['user-agent'] = userAgent;
  }

  static void addHeader(String key, String value){
    headers[key]=value;
  }
  static void removeHeader(String key){
    if(headers.containsKey(key)){
      headers.remove(key);
    }
  }

  static Future<Result> get(String path) async{
    var response = await Dio().get(apiServer + path, options: Options(headers: headers));
    return Result.response(response);
  }
  static Future<Result> post(String path, [Map<String,dynamic> data]) async{
    var response = await Dio().post(apiServer + path, data:data, options: Options(headers: headers));
    return Result.response(response);
  }
}

class Result{
  int statusCode = 200;
  int code = 0;
  String message='';
  String _body;
  Map<String, dynamic> data;
  List<dynamic> list;

  Result.response(Response response){
    this.statusCode=statusCode;
    this.init(response.data);
  }

  Result(int statusCode, String body){
    this.statusCode=statusCode;
    this._body=body;
    if(_body.isNotEmpty){
      var resultJson = json.decode(_body);

      this.init(resultJson);
    }
  }

  init(resultJson){
    print(json.encode(resultJson));
    if(resultJson != null && resultJson is Map<String, dynamic>){
      code = resultJson['code'];
      message = resultJson['message']??'';

      if(code==1 && resultJson['data']!=null && resultJson['data'].isNotEmpty){
        if(resultJson['data'] is Map){
          data = resultJson['data'];
        }else if(resultJson['data'] is List){
          list = resultJson['data'];
        }
      }
    }
  }
}